//
//  ChooseCityViewController.swift
//  zhende
//
//  Created by 陆文宇 on 2017/5/4.
//  Copyright © 2017年 chenliang. All rights reserved.
//

import UIKit

class ChooseCityViewController: YYController, UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating, UISearchBarDelegate {
    
    var chooseCityClosure: ((YYCity) -> Void)!
    
    @IBOutlet weak var cityTableView: UITableView!
    var searchController: UISearchController!
    
    var location = YYLocation.getLocationCity()
    var cities = [String: [YYCity]]()
    var groups: [String] = ["!"]
    
    override func yy_configNaviItem(_ naviItem: UINavigationItem) {
        super.yy_configNaviItem(naviItem)
        
        title = "城市选择"
        
        let back = UIBarButtonItem(title: "取消", style: .done, target: self, action: #selector(backAction))
        navigationItem.leftBarButtonItem = back
        
        let rightButton = UIBarButtonItem(image: UIImage(named:"refresh.png"), style: .plain, target: self, action: #selector(ChooseCityViewController.rightClick))
        navigationItem.rightBarButtonItem = rightButton
    }
    
    @objc func backAction() {
        dismiss(animated: true, completion: nil)
    }
    
    @objc func rightClick() {
        yy_showStatusHUD()
        yy_post(url: apiUrlPrex + "/area/all", success: { (data) in
            let list = data as! [Any]
            YYCity.create(list, isAsync: false)
            self.initData()
        }) { (errmsg) -> String? in
            return errmsg
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        navigationController?.navigationBar.isTranslucent = true
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        navigationController?.navigationBar.isTranslucent = false
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
//        automaticallyAdjustsScrollViewInsets = false
        
        configTableView()
        
        initData()
    }
    
    func configTableView() {
        let containerVC = SearchResultTableViewController()
        let containerNC = UINavigationController(rootViewController: containerVC)
        containerVC.viewController = self
        searchController  = UISearchController(searchResultsController: containerNC)
        searchController.searchResultsUpdater = self
//        searchController.dimsBackgroundDuringPresentation = false
//        searchController.hidesNavigationBarDuringPresentation = false
        searchController.searchBar.searchBarStyle = .minimal
        searchController.searchBar.backgroundColor = .white
        searchController.searchBar.tintColor = .darkGray
        searchController.searchBar.delegate = self

        cityTableView.tableHeaderView = searchController.searchBar
        cityTableView.sectionIndexColor = mainColor
        cityTableView.register(UITableViewCell.self, forCellReuseIdentifier: "cityCell")
        cityTableView.register(UINib(nibName: "Collection_TableViewCell", bundle: nil), forCellReuseIdentifier: "collectionCell")
    }
    
    func initData() {
        yy_showStatusHUD()
        
        self.cities.removeAll()
        self.groups = ["!"]
        
        YYCity.getAll(types: [1, 2, 3]).forEach { (city) in
            let firstCharacter = city.category
            
            if self.groups.contains(firstCharacter) {
                self.cities[firstCharacter]?.append(city)
            } else {
                self.groups.append(firstCharacter)
                self.cities[firstCharacter] = [city]
            }
        }
        
        self.groups.sort()
        self.groups.forEach({ (group) in
            self.cities[group]?.sort(by: { (c1, c2) -> Bool in
                return c1.name < c2.name
            })
        })
        
        cityTableView.reloadData()
        yy_dismissHUD()
    }
    
    func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
        searchBar.searchBarStyle = .prominent
    }
    
    func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
        searchBar.searchBarStyle = .minimal
    }
    
    func updateSearchResults(for searchController: UISearchController) {
        let searchVC = ((searchController.searchResultsController as! UINavigationController).viewControllers.first as! SearchResultTableViewController)
        searchVC.searchResults.removeAll()
        let p = NSPredicate(format: "name contains '\(searchController.searchBar.text!)'")
        _ = cities.map { (b) -> Void in
            let r = (b.value as NSArray).filtered(using: p) as! [YYCity]
            searchVC.searchResults.append(contentsOf: r)
        }
        searchVC.tableView.reloadData()
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return groups.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 1
        }
        return cities[groups[section]]!.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return 50
        }
        return 40
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            return 40
        }
        return 30
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "collectionCell", for: indexPath) as! Collection_TableViewCell
            cell.cityCollectionView.dataSource = cell
            cell.cityCollectionView.delegate = cell
            cell.viewController = self
            cell.cities = [location ?? "定位失败"]
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cityCell", for: indexPath)
            cell.textLabel?.text = cities[groups[indexPath.section]]![indexPath.row].name
            cell.textLabel?.font = titleFont
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let city = cities[groups[indexPath.section]]![indexPath.row]
        chooseCityClosure(city)
        backAction()
    }
    
    func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
        if indexPath.section == 0 {
            return false
        }
        return true
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if section == 0 {
            return "定位城市"
        }
        return groups[section]
    }
    
    func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        return groups
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        navigationItem.rightBarButtonItem?.isEnabled = false
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        navigationItem.rightBarButtonItem?.isEnabled = true
    }
    
    func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
        navigationItem.rightBarButtonItem?.isEnabled = false
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        navigationItem.rightBarButtonItem?.isEnabled = true
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
